import { useMcpServer } from "@renderer/queries";
import type { ToolCallResult } from "@shared/types/openai";
import { AlertTriangle, Check, Clock, Server, X } from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { ToolCallModal } from "./tool-call-modal";

interface ToolCallCardProps {
  toolCall: ToolCallResult;
  threadId?: string;
  messageId?: string;
  className?: string;
}

export function ToolCallCard({
  toolCall,
  threadId,
  messageId,
  className = "",
}: ToolCallCardProps) {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const { t } = useTranslation();

  // Get MCP server information
  const { data: mcpServer } = useMcpServer(toolCall.mcpServerId || "", {
    enabled: !!toolCall.mcpServerId,
  });

  const getStatusIcon = () => {
    switch (toolCall.status) {
      case "success":
        return <div className="h-2 w-2 rounded-full bg-[#38B865]" />;
      case "error":
        return <div className="h-2 w-2 rounded-full bg-[#D82525]" />;
      case "pending":
        return <div className="h-2 w-2 rounded-full bg-[#0056FE]" />;
      case "awaiting_approval":
        return <AlertTriangle className="h-4 w-4 text-blue-500" />;
      default:
        return <Clock className="h-4 w-4 text-gray-400" />;
    }
  };

  const getStatusText = () => {
    switch (toolCall.status) {
      case "success":
        return t("chat.tool-calls.status.success");
      case "error":
        return t("chat.tool-calls.status.error");
      case "pending":
        return t("chat.tool-calls.status.pending");
      case "awaiting_approval":
        return t("chat.tool-calls.status.awaiting-approval");
      default:
        return t("chat.tool-calls.status.unknown");
    }
  };

  const handleApprove = async (event: React.MouseEvent) => {
    event.stopPropagation();
    if (toolCall.status !== "awaiting_approval" || !threadId || !messageId)
      return;

    try {
      await window.service.mcpService.approveTool(
        threadId,
        messageId,
        toolCall.id,
      );
    } catch (_error) {}
  };

  const handleReject = async (event: React.MouseEvent) => {
    event.stopPropagation();
    if (toolCall.status !== "awaiting_approval" || !threadId || !messageId)
      return;

    try {
      const reason = "User rejected the tool call"; // TODO: Add rejection reason dialog
      await window.service.mcpService.rejectTool(
        threadId,
        messageId,
        toolCall.id,
        reason,
      );
    } catch (_error) {}
  };

  const handleClick = () => {
    setIsModalOpen(true);
  };

  const handleKeyDown = (event: React.KeyboardEvent) => {
    if (event.key === "Enter" || event.key === " ") {
      event.preventDefault();
      handleClick();
    }
  };

  return (
    <>
      <button
        type="button"
        className={`block w-full cursor-pointer rounded-[10px] border-0 bg-white px-3.5 py-3 hover:bg-[#F9F9F9] dark:bg-bg dark:hover:bg-[#2D2D2D] ${className}`}
        onClick={handleClick}
        onKeyDown={handleKeyDown}
      >
        <div className="flex w-full items-center justify-between gap-x-4">
          {/* Left: MCP Server Icon */}
          <div className="flex items-center gap-3">
            <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-muted">
              {mcpServer?.icon ? (
                <span className="text-xl">{mcpServer.icon}</span>
              ) : (
                <Server className="h-5 w-5 text-muted-fg" />
              )}
            </div>

            {/* Tool Name and MCP Server Name */}
            <div className="flex flex-col items-start gap-1">
              <h3 className="font-medium text-setting-fg text-sm">
                {toolCall.name}
              </h3>
              <p className="text-muted-fg text-xs">
                {mcpServer?.name || toolCall.mcpServerId || "Unknown Server"}
              </p>
            </div>
          </div>

          {/* Right: Execution Status */}
          <div className="flex items-center gap-3">
            {/* Status Icon and Text - Always show */}
            <div className="flex items-center gap-2">
              {getStatusIcon()}
              <span
                className={`text-sm ${
                  toolCall.status === "success"
                    ? "text-[#38B865]"
                    : toolCall.status === "error"
                      ? "text-[#D82525]"
                      : toolCall.status === "pending"
                        ? "text-[#0056FE]"
                        : "text-setting-fg"
                }`}
              >
                {getStatusText()}
              </span>
            </div>

            {/* Approval Buttons - Only show when awaiting approval */}
            {toolCall.status === "awaiting_approval" && (
              <div className="flex items-center gap-2">
                <button
                  type="button"
                  onClick={handleApprove}
                  className="flex items-center gap-1 rounded-md bg-green-500 px-2.5 py-1 text-white text-xs transition-colors hover:bg-green-600"
                >
                  <Check className="h-3 w-3" />
                  {t("chat.tool-calls.actions.allow")}
                </button>
                <button
                  type="button"
                  onClick={handleReject}
                  className="flex items-center gap-1 rounded-md bg-red-500 px-2.5 py-1 text-white text-xs transition-colors hover:bg-red-600"
                >
                  <X className="h-3 w-3" />
                  {t("chat.tool-calls.actions.reject")}
                </button>
              </div>
            )}
          </div>
        </div>
      </button>

      {/* Tool Call Details Modal */}
      <ToolCallModal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        toolCall={toolCall}
        mcpServer={mcpServer}
        threadId={threadId}
        messageId={messageId}
      />
    </>
  );
}
